// config.js
// ====================== 创建提示框 ======================
// 样式
const style = document.createElement('style');
style.textContent = `
  .collect-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 9999;
    display: none;
    justify-content: center;
    align-items: center;
  }
  .collect-message {
    background: white;
    padding: 20px 40px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    font-size: 16px;
    color: #333;
  }
  .collect-message.success { color: #4CAF50; }
  .collect-message.error { color: #f44336; }
`;
document.head.appendChild(style);

// 提示框元素
const overlay = document.createElement('div');
overlay.className = 'collect-overlay';
const message = document.createElement('div');
message.className = 'collect-message';
overlay.appendChild(message);
document.body.appendChild(overlay);

// 获取规格层级结构
function getSpecsStructure() {
    const specBlocks = document.querySelectorAll('.skuItem--uxMLmkRx'); // 规格区块（如颜色、尺寸）
    const specs = [];

    specBlocks.forEach(block => {
        const title = block.querySelector('.labelText--PsOAip_9')?.innerText.trim() || '未知规格'; // 规格名称（如“颜色”）
        const options = Array.from(block.querySelectorAll('.content--TiXrAN07 .valueItem--GzWd2LsV')).map(item => ({
            element: item, // 规格选项的DOM元素
            name: item.querySelector('span')?.innerText, // 规格值（如“红色”）
        }));
        specs.push({ title, options });
    });

    return specs;
}

// 生成所有可能的组合
function generateCombinations(specs) {
    const combinations = [];
    const backtrack = (currentSpecIndex, currentPath) => {
        if (currentSpecIndex === specs.length) {
            combinations.push([...currentPath]);
            return;
        }
        for (const option of specs[currentSpecIndex].options) {
            currentPath.push({...option, title: specs[currentSpecIndex].title});
            backtrack(currentSpecIndex + 1, currentPath);
            currentPath.pop();
        }
    };
    backtrack(0, []);
    return combinations;
}

// 控制提示框显示/隐藏的函数
function showMessage(text, isSuccess = true) {
    message.className = `collect-message ${isSuccess ? 'success' : 'error'}`;
    message.textContent = text;
    overlay.style.display = 'flex';
}

function hideMessage() {
    overlay.style.display = 'none';
}

const TAOBAO_CONFIG = {
    // 通用配置（适用于所有淘宝页面）
    common: {
        matches: ["*://*.taobao.com/*"], // 匹配所有淘宝页面
        buttonStyle: {
            zIndex: 1000,
            padding: '5px 20px',
            background: '#ff5500',
            borderRadius: '5px',
            color: 'white',
            border: 'none',
            cursor: 'pointer'
        },
    },

    // 不同页面类型的独立配置
    pages: [
        {
            // 首页
            name: "首页",
            // 通过 URL 或 DOM 特征识别页面类型
            condition: {
                urlPattern: "*://www.taobao.com", // URL 匹配规则
                // 或通过 DOM 特征识别（如页面中存在特定元素）
                domSelector: "", // 仅当该元素存在时生效
            },
            cardSelector: ".tbpc-col .tb-pick-content-item", // 商品卡片选择器
            extractor: (card) => ({
                title: card.querySelector(".info-wrapper-title-text")?.textContent.trim(),
                price: card.querySelector(".price-value")?.textContent.trim(),
                image: card.querySelector(".product-img")?.src,
                link: card.querySelector("a")?.href || "",
            }),
            buttonStyle: {
                top: '10px',
                right: '10px',
                position: "absolute",
            },
        },
        {
            // 搜索页
            name: "搜索",
            // 通过 URL 或 DOM 特征识别页面类型
            condition: {
                urlPattern: "*://s.taobao.com/*", // URL 匹配规则
                // 或通过 DOM 特征识别（如页面中存在特定元素）
                domSelector: "", // 仅当该元素存在时生效
            },
            cardSelector: ".tbpc-col", // 商品卡片选择器
            extractor: (card) => ({
                title: card.querySelector(".title--qJ7Xg_90 > span")?.textContent.trim(),
                price: card.querySelector(".priceInt--yqqZMJ5a")?.textContent.trim(),
                image: card.querySelector(".mainPicAdaptWrapper--V_ayd2hD .mainPic--Ds3X7I8z")?.src,
                link: card.querySelector("a")?.href || "",
            }),
            buttonStyle: {
                top: '10px',
                right: '10px',
                position: "absolute",
            },
        },
        {
            // 活动页
            name: "活动",
            condition: {
                urlPattern: "*://huodong.taobao.com/*",
            },
            cardSelector: ".tbpc-ark-act-item-pc6-m3--item--3ZuT6Jd",
            extractor: (card) => ({
                title: card.querySelector(".rax-view-v2.tbpc-ark-act-item-pc6-m3--titleWrapper--2DvBzeU")?.textContent.trim(),
                price: card.querySelector(".rax-text-v2.tbpc-ark-act-item-pc6-m3--price--zdCE2LE")?.textContent.trim(),
                image: card.querySelector(".rax-image")?.src,
                link: card?.href || "",
            }),
            buttonStyle: {
                top: '10px',
                right: '10px',
                position: "absolute",
            }
        },
        {
            // 咸鱼
            name: "咸鱼",
            condition: {
                urlPattern: "*://2.taobao.com/*",
            },
            cardSelector: ".web--view--zpjRVPN.cursor-pointer",
            extractor: (card) => ({
                title: card.querySelector(".system-font.select-none")?.textContent.trim(),
                price: card.querySelector(".web--view--zpjRVPN.items-end.leading-none .web--view--zpjRVPN.relative")?.textContent.trim(),
                image: card.querySelector(".web--view--zpjRVPN.relative img")?.src,
                link: card.querySelector("a")?.href || "",
            }),
            buttonStyle: {
                right: '10px',
                position: "absolute",
                background: '#ffe60f',
            },
        },
        {
            // 淘宝详情页
            name: "淘宝详情页",
            // 通过 URL 或 DOM 特征识别页面类型
            condition: {
                urlPattern: "*://item.taobao.com", // URL 匹配规则
                // 或通过 DOM 特征识别（如页面中存在特定元素）
                domSelector: "", // 仅当该元素存在时生效
            },
            cardSelector: "html", // 商品卡片选择器
            extractor: async () => {
                const specs = getSpecsStructure();
                const combinations = generateCombinations(specs);
                const results = [];
                for (let i = 0; i < combinations.length; i++) {
                    const combination = combinations[i];
                    let isValid = true;
                    let imgUrl = ''
                    // 依次点击当前组合的规格
                    for(let i = 0; i < combination.length; i++) {
                        const option = combination[i];
                        try {
                            const isExist = option.element.classList.contains('isSelected--YrA6x4Yj')
                            if(!isExist) {
                                option.element.click(); // 模拟点击
                            }
                            await new Promise(resolve => setTimeout(resolve, 200)); // 等待价格更新
                            imgUrl = option.element.querySelector('img')?.src || imgUrl
                            // 检查是否可选（如灰色不可点击）
                            if (option.element.classList.contains('isDisabled--x_T2h1sh') && i === combination.length -1) {
                                isValid = false;
                                break;
                            }
                        } catch (error) {
                            isValid = false;
                            break;
                        }
                    }

                    // 如果组合有效，记录价格
                    if (isValid) {
                        const price = document.querySelector('.text--fZ9NUhyQ')?.innerText || document.querySelector('.priceText--YZzF3UMh')?.innerText;
                        const specs = {}
                        for(let i = 0; i < combination.length; i++) {
                            specs[combination[i].title] = combination[i].name
                        }
                        // const specNames = combination.map(opt => opt.name);
                        results.push({ specs, price, imgUrl });
                    }

                    // 更新进度提示
                    showMessage(`已采集 ${i + 1}/${combinations.length} 种组合...`);
                }

                let imageTexts = document.querySelectorAll('.descV8-container img')
                let imageText = []
                for (let i = 0; i < imageTexts.length; i++) {
                    if(i + 1 !== imageTexts.length) {
                        const imgUrl = imageTexts[i]?.getAttribute("data-src")
                        imageText.push(imgUrl)
                    }
                }

                return {skus: results, imageTexts: imageText};
            },
            buttonStyle: {
                position: 'fixed',
                bottom: '50px',
                left: '10px'
            },
        },
    ],
};
